import type { App } from 'vue'

/**
 * 自动获取焦点
 */
export function focusDirective(app: App) {
  app.directive('focus', {
    mounted(el: HTMLElement) {
      if(el.tagName === 'INPUT') {
        el.focus()
      }
      let elChildren: HTMLCollection = el.children || []
      if(elChildren && elChildren.length) {
        inputAutoFocus(elChildren)
      }
    }
  })
}

function inputAutoFocus(els: HTMLCollection) {
  for(let i = 0; i < els.length; i++) {
    let el = els.item(i)
    if(el?.tagName === 'INPUT') {
      (el as HTMLInputElement).focus()
    }
    let elChild = (el?.children || []) as HTMLCollection
    if(elChild && elChild.length) {
      inputAutoFocus(elChild)
    }
  }
}

/**
 * 图片懒加载
 */
export function lazyDirective(app: App) {
  app.directive('lazy', {
    mounted(el: HTMLImageElement) {
      const src = el.src
      el.src = ''
      const observer = new IntersectionObserver(([{ isIntersecting }]) => {
        if(isIntersecting) {
          el.src = src
          observer.unobserve(el)
        }
      })
      observer.observe(el)
    }
  })
}